package  de.cube3d.blitwit.render
{
	import flash.display.BitmapData;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import de.cube3d.blitwit.space.SpaceObject;
	
	public class BlitSpriteBitmap extends SpaceObject 
	{
		protected var _bm:BitmapData;
		public function BlitSpriteBitmap(bm:BitmapData, x:Number, y:Number) 
		{
			super(x, y, bm.width, bm.height);
			_bm = bm;
		}
		
		private static var _SRC:Rectangle = new Rectangle();
		private static var _DST:Point = new Point();
		private static var _m:Matrix = new Matrix();
		override public function draw(bm:BitmapData, x:Number, y:Number, scale:Number, clipRect:Rectangle):void {
			//blit(bm, _SRC, _DST,clipRect, scale);
			
			if (scale == 1) {
				_DST.x = int(Math.max((x), (clipRect.x)));
				_DST.y = int(Math.max((y), (clipRect.y)));
				
				_SRC.x = _DST.x-int(x);
				_SRC.y = _DST.y-int(y);
				_SRC.width = Math.min(Math.min(_bm.width,int(clipRect.width)), int(clipRect.width) + int(clipRect.x) - int(x));
				_SRC.height = Math.min(Math.min(_bm.height,int(clipRect.height)), int(clipRect.height) + int(clipRect.y) - int(y));
				
				bm.copyPixels(_bm, _SRC, _DST);
			} else {
				_DST.x = Math.max((x), (clipRect.x));
				_DST.y = Math.max((y), (clipRect.y));
				
				_SRC.x = _DST.x-(x);
				_SRC.y = _DST.y-(y);
				_SRC.width = Math.min(Math.min(_bm.width,(clipRect.width)), (clipRect.width) + (clipRect.x) - (x));
				_SRC.height = Math.min(Math.min(_bm.height,(clipRect.height)), (clipRect.height) + (clipRect.y) - (y));
				
				_m.a = _m.d = scale;
				_m.tx = _DST.x-_SRC.x;
				_m.ty = _DST.y-_SRC.y;
				bm.draw(_bm, _m, null, null,clipRect, true);
			}
		}
		
		override public function contains(x:Number, y:Number):Boolean {
			if (!super.contains(x, y)) return false;
			var argb:uint = _bm.getPixel32(x-this.x, y-this.y);
			return (argb >>> 24) > 128;
		}
		
		override public function getCopy(overwrite:SpaceObject = null):SpaceObject {
			if (overwrite == null)
				return new BlitSpriteBitmap(_bm, x, y);
			var cp:BlitSpriteBitmap = super.getCopy(overwrite) as BlitSpriteBitmap;
			cp._bm = _bm;
			cp._currentRect.width = width;
			cp._currentRect.height = height;
			return cp;
		}
	}

}